package com.ling.greedy.snake.game.ui.pages.game.widget

import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.ling.greedy.snake.game.R
import com.ling.greedy.snake.game.model.Direction
import kotlin.math.abs

@Composable
fun GameTouchPad(modifier: Modifier = Modifier, minScrollSize : Dp,  onChangeDirection : (newDirection : Direction) -> Unit){
    val isDirectionChanged = remember { mutableStateOf(false) } // 标记是否已处理方向
    Box(
        modifier = modifier
            .pointerInput(Unit) {
                detectDragGestures(
                    onDragEnd = { isDirectionChanged.value = false },
                    onDragStart = { isDirectionChanged.value = false }
                ) { _ , dragAmount ->
                    val (x, y) = dragAmount
                    val swipeThreshold = minScrollSize.toPx() // 滑动阈值
                    if (!isDirectionChanged.value && (abs(x) > swipeThreshold || abs(y) > swipeThreshold)) {
                        isDirectionChanged.value = true
                        val direction = when {
                            abs(x) > abs(y) -> if (x > 0) Direction.RIGHT else Direction.LEFT
                            else -> if (y > 0) Direction.DOWN else Direction.UP
                        }
                        onChangeDirection(direction)
                    }
                }
            }
    ){
        Image(
            painter = painterResource(R.drawable.ic_up),
            contentDescription = null,
            modifier = Modifier.size(20.dp).align(Alignment.TopCenter)
        )
        Image(
            painter = painterResource(R.drawable.ic_right),
            contentDescription = null,
            modifier = Modifier.size(20.dp).align(Alignment.CenterEnd)
        )
        Image(
            painter = painterResource(R.drawable.ic_down),
            contentDescription = null,
            modifier = Modifier.size(20.dp).align(Alignment.BottomCenter)
        )
        Image(
            painter = painterResource(R.drawable.ic_left),
            contentDescription = null,
            modifier = Modifier.size(20.dp).align(Alignment.CenterStart)
        )
    }
}

@Preview
@Composable
fun PreviewGamePage(){
    GameTouchPad(minScrollSize = 10.dp){}
}